﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Utility
{
    public static class HttpHelper
    {
        #region get and post
        public static string GetRequest(string url, string Method, string ContentType, int Timeout = 3)
        {
            /*使用
            string url="Http://127.0.0.1/login.jsp?Name=zhangshi&Age=30&Submit=%cc%E+%BD%BB";
            string res = HttpHelper.GetRequest(url, 6000);
            if (res != null)
            {
                T mes = JsonHelper.DeserializeJsonToObject<T>(res)
            }
            */
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = Method;
            request.ContentType = ContentType;
            request.UserAgent = null;
            request.Timeout = Timeout * 60 * 1000;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public static string HttpPost(string Url, string Method, string ContentType, string postDataStr, int Timeout = 3)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.ContentType = ContentType;
            request.Method = Method;
            request.Timeout = Timeout * 60 * 1000;

            byte[] btBodys = Encoding.UTF8.GetBytes(postDataStr);
            request.ContentLength = btBodys.Length;
            request.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            HttpWebResponse response = response = (HttpWebResponse)request.GetResponse();
            //HttpWebResponse response;
            //try { 
            //    response = (HttpWebResponse)request.GetResponse(); 
            //}
            //catch (WebException ex)
            //{
            //    response = (HttpWebResponse)ex.Response;
            //}
            StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();

            response.Close();
            streamReader.Close();
            request.Abort();
            response.Close();

            return responseContent;
        }
        #endregion

        #region post 异步
        public static async Task<string> PostAsync(string url, Dictionary<string, string> parameter, string contenttype)
        {
            using (HttpClient client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(parameter);
                //var content = new StringContent(parameter, Encoding.UTF8, contenttype);
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    return result;
                }
                else
                {
                    return $"Request failed with status code {response.StatusCode}";
                }
            }
        }

        public static async Task<List<string>> AsyncTaskPost(List<string> urls, Dictionary<string, string> data)
        {
            var results = new List<string>();
            var tasks = new List<Task<string>>();

            foreach (var url in urls)
            {
                data = new Dictionary<string, string>()
                {
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129231!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129232!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129233!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129234!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129235!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129236!\",\"return_message\":null}]}" },
                  //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129237!\",\"return_message\":null}]}" },
                  { "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\""+GeneralMethod.ConvertDateTime(DateTime.Now)+"\",\"return_message\":null}]}" }
                };

                var content = new FormUrlEncodedContent(data);
                var client = new HttpClient();
                tasks.Add(client.PostAsync(url, content).Result.Content.ReadAsStringAsync());
            }

            var completedTasks = await Task.WhenAll(tasks);

            foreach (var result in completedTasks)
            {
                results.Add(result);
            }

            return results;
        }

        public static  async void PushSend(string process, string url, string method, string contenttype, List<object> parameter)
        {
            // Usage:
            var urls = new List<string>()
            {
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew",
              "https://localhost:44325/EpicorWebService_FISLabor.asmx/CreateLaborNew"
            };
            var data = new Dictionary<string, string>()
            {
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129231!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129232!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129233!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129234!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129235!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129236!\",\"return_message\":null}]}" },
              //{ "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\"1685129237!\",\"return_message\":null}]}" },
              { "json", "{\"LaborDtl\":[{\"company\":\"CL-DG\",\"jobnum\":\"MP202305270001\",\"assemblypartnum\":\"4600-01-0105\",\"processname\":\"LD_BOND_SUBMOUNT\",\"payrolldate\":\"2023-04-19T00:00:00\",\"productionlot_c\":\"ADV2-LA-230419-01-000\",\"employeenum\":\"C00981\",\"status\":null,\"create_time\":\"2023-04-19T18:48:13\",\"transaction_seq\":null,\"laborqty\":200.0,\"scrapqty\":0.0,\"discrepqty\":0.0,\"scrapreasoncode\":\" \",\"discrprsncode\":\" \",\"labornote\":null,\"type\":\"oracle\",\"proactivikey_c\":\""+GeneralMethod.ConvertDateTime(DateTime.Now)+"\",\"return_message\":null}]}" }
            };

            for (int i = 0; i < 10; i++)
            {
                var responses = await AsyncTaskPost(urls, data);
            }
        }
        #endregion

        #region  异步多线程
        public static async Task<List<string>> SendRequestsAsync(List<string> urls)
        {
            List<Task<string>> tasks = new List<Task<string>>();
            using (HttpClient client = new HttpClient())
            {
                foreach (string url in urls)
                {
                    tasks.Add(SendRequestAsync(client, url));
                }
                await Task.WhenAll(tasks);
            }

            List<string> results = new List<string>();
            foreach (Task<string> task in tasks)
            {
                results.Add(task.Result);
            }
            return results;
        }

        private static async Task<string> SendRequestAsync(HttpClient client, string url)
        {
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new Exception($"Request failed with status code {response.StatusCode}");
            }
        }
        #endregion
    }
}
